package com.example.human_resource_management.controller;

import com.example.human_resource_management.common.ResponseData;
import com.example.human_resource_management.config.JwtUtils;
import com.example.human_resource_management.entry.dto.AdminLoginDto;
import com.example.human_resource_management.entry.dto.AdminUpdateDto;
import com.example.human_resource_management.entry.po.Admin;
import com.example.human_resource_management.service.AdminService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
public class AdminController {
    @Resource
    private AdminService adminService;

    @PostMapping("login")
    public ResponseData<Map<String, Object>> login(@RequestBody AdminLoginDto adminLoginDto) {
        Admin admin = adminService.login(adminLoginDto);
        if (admin != null) {
            String token = JwtUtils.generateToken(admin.getAdminId());
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("role", admin.getRole());
            return ResponseData.ok(data);
        } else {
            return ResponseData.warn("用户名或密码错误");
        }
    }

    /**
     * 获取所有管理员列表
     */
    @GetMapping("/list")
    public ResponseData<List<Admin>> getAllAdmins() {
        List<Admin> admins = adminService.getAllAdmins();
        return ResponseData.ok(admins);
    }

    /**
     * 更新管理员信息
     * @param updateDto 更新数据
     */
    @PutMapping("/update")
    public ResponseData<String> updateAdmin(@RequestBody AdminUpdateDto updateDto) {
        boolean success = adminService.updateAdmin(updateDto);
        return success ?
                ResponseData.ok("管理员更新成功") :
                ResponseData.warn("管理员更新失败");
    }
}